
// testDlg.cpp : implementation file
//

#include "stdafx.h"



#include "test.h"
#include "testDlg.h"
#include "shared\dbg.h"
#include <mmsystem.h>


#ifdef _DEBUG
#define new DEBUG_NEW
#endif
using namespace avlib;

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	ON_WM_PAINT()
END_MESSAGE_MAP()


// CtestDlg dialog




CtestDlg::CtestDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CtestDlg::IDD, pParent)
	, m_progrss(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);


	video = NULL;
	recorder = NULL;
	screen = NULL;
	sys = NULL;
	m_avi = NULL;

	bRecording = false;
	bConverting = false;

	m_id  = 0;
}

void CtestDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_COMBO1, mVideoSelector);
	DDX_Control(pDX, IDC_COMBO2, mAudioSelector);
}

BEGIN_MESSAGE_MAP(CtestDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDOK, &CtestDlg::OnBnClickedOk)
	
	ON_BN_CLICKED(IDC_RECORD, &CtestDlg::OnBnClickedRecord)
	ON_BN_CLICKED(IDC_CONVERT, &CtestDlg::OnBnClickedConvert)
	ON_CBN_SELCHANGE(IDC_COMBO1, &CtestDlg::OnCbnSelchangeCombo1)
	ON_CBN_SELCHANGE(IDC_COMBO2, &CtestDlg::OnCbnSelchangeCombo2)
	ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()


// CtestDlg message handlers

BOOL CtestDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	TestIt();



	
	vgl::ShapeManager::init_all();
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CtestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.


static vgl::Rectangle *rect= NULL;

void CtestDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{

		
		CPaintDC dc(this);
		
		if(rect == NULL)
			rect = new vgl::Rectangle(300,20,100,50);

		vgl::graphics_t g(dc);

		if(rect) rect->draw(g);
		
		//Gdiplus::Pen 
		//g.DrawRectangle(

		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CtestDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



static int iTimes = 0;
int FPS = 50;
static int gFrame = 0;

void CALLBACK waveInProc(HWAVEIN hwi,UINT uMsg,DWORD dwInstance,DWORD dwParam1,DWORD dwParam2)
{

	static LPBYTE gSndBuffer = NULL;
	static UINT gSndBufSZ = 0;
	static UINT gSZ = 0;


	WAVEHDR *pHdr=NULL;
	MMRESULT mRes = 0;
	switch(uMsg)
	{
		case WIM_CLOSE:
			break;

		case WIM_DATA:
			{
				CtestDlg* dlg = (CtestDlg*)dwInstance;

				if(gSndBuffer == NULL){
					//gSndBufSZ = pAvi->mFormat.nAvgBytesPerSec/FPS;
					gSndBufSZ = dlg->m_avi->get_audio_format().nAvgBytesPerSec/FPS;
					gSndBuffer = (LPBYTE)malloc(gSndBufSZ);
				}

				pHdr = (WAVEHDR*) dwParam1;
				if(WHDR_DONE==(WHDR_DONE &pHdr->dwFlags))
				{

					
#if 0
					dlg->m_wav->add_pcm_data(pHdr->lpData,pHdr->dwBytesRecorded);
					
					iTimes++;

					char fname[100];
					sprintf(fname,"bmp%04d.bmp",iTimes);
					BmpFile bmp(fname);
					bmp.save_bmp(dlg->screen->get_bmp());
					//dlg->screen
#else
					//gSZ the current global buffer size
					//ccp  bytes processed for this arrived data

					int ccp = 0;
					while(pHdr->dwBytesRecorded > ccp){
						int av = min(gSndBufSZ-gSZ,pHdr->dwBytesRecorded-ccp);//free space available

						memcpy(gSndBuffer+gSZ,pHdr->lpData+ccp,av);

						gSZ += av;
						ccp += av;
						
						if(gSZ == gSndBufSZ){
						
							if(dlg->m_video_id == 0){
								assert(dlg->screen);
								dlg->m_avi->AppendVideoFrame(dlg->screen->get_bits());
							}else{
								assert(dlg->video);
								dlg->m_avi->AppendVideoFrame(dlg->video->get_bits());
							}
							//
							dlg->m_avi->AppendSoundSamples((LPVOID)gSndBuffer,gSZ);
							//av = gSndBufSZ;
							gSZ = 0;

							gFrame++;

							char tmp[100];

							sprintf(tmp,"encoding frame %d",gFrame);
							dlg->on_stdout_line(NULL,tmp);
						}
					}


					
#endif
					if(dlg->bRecording)
						mRes = waveInAddBuffer(hwi,pHdr,sizeof(WAVEHDR));

				}

			}
			break;

		case WIM_OPEN:
			break;

		default:
			break;
	}
	
	//log("callback %d",iTimes++);
}


void CtestDlg::TestIt(){

	HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	if (FAILED(hr)){
		log("CoInitializeEx error");
		return ;
	}
	
	sys = new System();

	sys->EnumDevices();

	//mVideoSelector.AddString("Screen");
	
	for(int i=0; i< sys->mVideoDevices.size();i++){
		mVideoSelector.AddString(sys->mVideoDevices[i]->dev_name.c_str());
	}

	for(int i=0; i< sys->mAudioDevices.size();i++){
		mAudioSelector.AddString(sys->mAudioDevices[i]->dev_name.c_str());
	}

}

void CtestDlg::StopRecord(){

	bRecording = false;
	if(recorder){
		recorder->stop();
		delete(recorder);
		recorder = 0;
	}
	if(screen){
		screen->stop();
		delete(screen);
		screen = 0;
	}
	if(video){
		video->stop();
		delete(video);
		video = 0;
	}

	/*if(m_avi){
		m_avi->close();
		delete m_avi;
		m_avi = 0;
	}*/
}

void CtestDlg::StartRecord(){
	
	int v_idx = mVideoSelector.GetCurSel();
	int a_idx = mAudioSelector.GetCurSel();

	if(v_idx < 0 ||a_idx < 0){
		MessageBox("you must select a video source and a audio source","",MB_OK);
		return;
	};


	//get audio device waveid
	int a_dev_id =  sys->mAudioDevices[a_idx]->dev_id;
	int v_dev_id = m_video_id = v_idx;

	CRect rc;
	rc.left=0;
	rc.right = 320;
	rc.top = 0;
	rc.bottom = 240;

	


	if(m_video_id >=1 && video == NULL){
		video = new VideoRecorder();
		video->init();
		video->set_capture_size(rc.Width(),rc.Height());
		video->set_fps(FPS);
		//video->open(v_dev_id,GetSafeHwnd());
		video->open(v_dev_id,NULL);
		video->start();
	};

	if(m_video_id == 0 && screen == NULL){

		screen = new ScreenRecorder();
		screen->set_param(FPS,true);
		screen->set_region(&rc);
		//screen->get_region(rc);
		screen->start();
	}


	if(recorder == NULL){
		recorder = new AudioRecorder();
		recorder->open(a_dev_id,(DWORD_PTR)waveInProc,(DWORD_PTR)this);

		//m_wav = new WaveFile("g:\\tv\\tst.wav");
		//m_wav->init(2,44100,16);
		
		bRecording = true;
		recorder->start();
	}


	if(m_avi == NULL){
		m_avi = new AviFile("test.cap.avi");
		m_avi->set_fps(FPS);
		m_avi->InitVideo(rc.Width(),rc.Height(),32);
		m_avi->InitAudio((LPWAVEFORMAT)(recorder->get_format()));
	}
}

void CtestDlg::on_stdout_line(cparam_t param,const std::string  & str){
	m_progrss = str.c_str();
	//UpdateData(false);
	GetDlgItem(IDC_EDIT1)->SetWindowText(m_progrss);
	log("%s",str.c_str());
}


void CtestDlg::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here
	
	OnOK();
}




void CtestDlg::OnBnClickedRecord()
{
	bRecording = ! bRecording;
	if(bRecording = true){
		StartRecord();
		GetDlgItem(IDC_RECORD)->SetWindowTextA("stop record");
	}else{
		StopRecord();
		GetDlgItem(IDC_RECORD)->SetWindowTextA("start record");
	}
}

void CtestDlg::OnBnClickedConvert()
{
	if(bRecording){
		bRecording = false;
		StopRecord();

		//save avi and close file
		
	}

	//save avi
	if(m_avi){
			m_avi->close();
			delete m_avi;
			m_avi = 0;
	}


	if(m_id == 0){
	
		char *prog = "G:\\media_tools\\old\\mencoder\\MPlayer-rtm-svn-34401\\mencoder.exe";
		char *args = "test.cap.avi -ovc x264 -oac mp3lame -o test.cap.mp4";
		m_id = Executor::exec(prog,args,this,0);
		bConverting = true;

		return;
	}

	bConverting = !bConverting;
	if(!bConverting){
		GetDlgItem(IDC_BUTTON1)->SetWindowText("resume");
		Executor::pause(m_id);
	}else{
		GetDlgItem(IDC_BUTTON1)->SetWindowText("pause");
		Executor::resume(m_id);
	}
}

void CtestDlg::OnCbnSelchangeCombo1()
{
	// TODO: Add your control notification handler code here
	StopRecord();
}

void CtestDlg::OnCbnSelchangeCombo2()
{
	// TODO: Add your control notification handler code here
	StopRecord();
}

void CtestDlg::OnMouseMove(UINT nFlags, CPoint point)
{
	// TODO: Add your message handler code here and/or call default


	//if(rect && rect->hit_test(vgl::point_t(point.x,point.y),4)){
	if(rect && rect->hit_ctrl(vgl::point_t(point.x,point.y))){
	

		HCURSOR hCursor = ::LoadCursor(NULL,IDC_SIZENS );
		::SetCursor(hCursor);

	}

	__super::OnMouseMove(nFlags, point);
}
